package top.lvkun.basic.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import top.lvkun.basic.constant.Constant;
import top.lvkun.basic.utils.AjaxResult;
import top.lvkun.basic.utils.RedisUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //从请求头中获取userToken
        String userToken = request.getHeader("userToken");
        //判断userToken是否为空
        if(StringUtils.hasText(userToken)){
            //以userToken为key取出redis中存储json对象
            String userJsonStr = RedisUtils.INSTANCE.get(userToken);
            if(StringUtils.hasText(userJsonStr)){
                //刷新redis中过期时间
                RedisUtils.INSTANCE.set(userToken,userJsonStr, Constant.EXPIRE_TIME_IN_REDIS);
                return true;
            }
        }

        //3.未登录时，给出相应提示
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("noUser");
        /**
         * 下面这一堆代码：就是SpringMVC的@ResponseBody注解的底层实现代码
         */
        //利用jackson工具将对象转化为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(ajaxResult);
        //利用响应对象的输出流输出这个json字符串
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonStr);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }
}
